<?php
//首页作业中心
Namespace Api\Controller;
use Think\Controller;
use Api\Model;
class HomepageApiController extends ApiBaseController {

    //首页信息
    public function getHomeData(){
        $strUsername =$this->getDefaultUserName();
        $mdlAd =new \Api\Model\AppADModel();
        $arrBanner =   $mdlAd->getAD("getHomeData","imageUrl","url");
        $mdlParent =new Model\AppParentsModel();
        $arrSource = $mdlParent->getCourseList($strUsername,"imageUrl","name","courseId");
        $arrSource=array(); // 测试数据
        for($i=0;$i<3;$i++){
            $arrSource[] =array(
                "imageUrl"=>"https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=1253763438,4067203203&fm=58&s=56F0A5767BC0BF0DF5B5DDA403002021&bpow=121&bpoh=75",
                "name"=>"测试课程",
                "courseId"=>1
            );
        }
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrResult = $mdlLesson->getRecommendList("getHomeData");
        $arrData = array("bannerList"=>$arrBanner,"msgList"=>array(),"myCourseList"=>$arrSource,"recommendList"=>$arrResult);
        ShowJsonReturnAndDie($arrData);
    }


     //今日打卡详情
    public function getCardDetail(){
        $strShareUrl=$this->getH5BaseUrl()."share/";
        $strUsername = $this->getDefaultUserName();
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrResult0 =  $mdlLesson->getTodayCard($strUsername);
        $arrResult=array();
        foreach($arrResult0 as $row)
        {
            $arrResult[$row["cardminutes"]]=$row["sumcardminutes"];
        }
        $arrResult["url"]= $strShareUrl;
        ShowJsonReturnAndDie($arrResult);
    }

    //获取推荐列表
    public function getRecommendList(){
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrResult = $mdlLesson->getRecommendList("getRecommendList");
        ShowJsonReturnAndDie($arrResult);
    }
    //获取磨耳朵
    public function getListening(){
        $mdlAd =new Model\AppADModel();
        $arrAD =  $mdlAd->getAD("getListening","imageUrl","url");
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrRecommendWithReadcount =
        $arrResult = array(
            "listening100"=>$mdlLesson->getlistening100Url(),
            "animation100"=>$mdlLesson->getanimation100Url(),
            "bannerList"=>$mdlAd->getAD("getListening","imageUrl","url"),
            "recommendList"=>$mdlLesson->getRecommendList("getListening")
        );
        ShowJsonReturnAndDie($arrResult);
    }
    //获取儿歌以及分类
    public function getMusicClasses(){
        $iType =I("type");
        $iType1 = $iType;
        //$iType= 6;
        $mdlLessones =new \Api\Model\AppLessonModel();
        //  1 //1:听儿歌 2：听诗歌 3：听对话 4：听绘本 5:阅读 6:口语
        switch($iType)
        {
            case 5:
                $arrResult0= $mdlLessones->getYueDuSubType();
                $arrResult = array();
                foreach($arrResult0 as $row)
                {
                    $arrResult[]= array(
                        "title"=>$row["categoryname"],  //分类名称
                        "classId"=>$row["id"]
                    );
                }
                break;
            case 6:
                /* categoryname,id */
                $arrResult0= $mdlLessones->getKouYuSubType();
                $arrResult = array();
                foreach($arrResult0 as $row)
                {
                    $arrResult[]= array(
                        "title"=>$row["categoryname"],  //分类名称
                        "classId"=>$row["id"]
                    );
                }
                break;
            default:
                $iDbTypeID = $mdlLessones->getMoErDuoTypeIDbyRequestID($iType);

                $arrResult = $mdlLessones->getMusicClasses($iDbTypeID);

                break;
        }

        ShowJsonReturnAndDie($arrResult);
    }

    //获取分类儿歌列表
    public function getMusicList(){
        $iClassID = I("classId");
        $strUsername=$this->getDefaultUserName();
        //$iClassID = 1 ;
        $mdlLessones =new \Api\Model\AppLessonModel();
        $arrResult = $mdlLessones->getBookList($iClassID,$strUsername);
        ShowJsonReturnAndDie($arrResult);
    }
    //获取诗歌列表
    public function getPoetryList(){
        $strUsername =$this->getDefaultUserName();
        $mdlLessones =new \Api\Model\AppLessonModel();
        $arrResult = $mdlLessones->getPoetryList($strUsername);
        ShowJsonReturnAndDie($arrResult);
    }
    //我的磨耳朵
    public function getMyListening(){
        $strUsername = $this->getDefaultUserName();
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrStudent = $mdlParent->getStudentByUsername($strUsername);
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrCard0 = $mdlLesson->getTodayCard($strUsername);
        $arrCard = array();
        $iTotalMinutes = 0;
        foreach($arrCard0 as $row)
        {
            $iMinutes = $row["sumcardminutes"];
            $iTotalMinutes+=$iMinutes;
            $arrCard[]=array(
                "type" =>$row["cardtype"],
                "duration"=>$iMinutes
            );
        }
        $arrCardHistory0 = $mdlLesson->getTodayCard($strUsername);
        $arrCardHistory = array();
        $iTotalMinutesHistory = 0;
        foreach($arrCardHistory0 as $rowHistory)
        {
            $iMinutesTemp = $rowHistory["sumcardminutes"];
            $iTotalMinutesHistory+=$iMinutesTemp;
            $arrCardHistory[]=array(
                "type" =>$rowHistory["cardtype"],
                "duration"=>$iMinutesTemp
            );
        }
        $arrResult = array(
            "level"=>$arrStudent["applevel"],
            "subLevel"=>$arrStudent["appsublevel"],
            "todayList"=>$arrCard,
            "todayTotalDuration"=>$iTotalMinutes,
            "historyList"=>$arrCardHistory,
            "historyTotalDuration"=>$iTotalMinutesHistory
        );

        ShowJsonReturnAndDie($arrResult);
    }



     //时长录入
    public function commitDuration(){
        $strUsername = $this->getDefaultUserName();
        $strType = trim(I("type"));
        $iDuration =I("duration");
        if(!is_numeric($iDuration))
        {
            ShowJsonReturnAndDie(null,true,"请输入有效时长");
        }
        $mdlLesson =new \Api\Model\AppLessonModel();
        $db  = $mdlLesson->getCardDb();
        $db->add(array(
            "cardtype"=>$strType,
            "cardminutes"=>$iDuration,
            "addtime"=>date("Y-m-d H:i:s"),
            "username"=>$strUsername
            ));
        //$bContinue=true;
        //$i=0;
        //$arrInputValues =array();
        //while($bContinue){
        //    $i=$i+1;
        //    $strID =trim(I("device_".$i));
        //    if($strID=="")
        //    {
        //        $bContinue = false;
        //    }else{
        //        $iTime = I("time_".$i);
        //        if(!is_numeric($iTime))
        //        {
        //            ShowJsonReturnAndDie(null,true,"请输入有效时长");
        //        }
        //        $arrInputValues[] = array(
        //            "cardtype"=>$strID,
        //            "cardminutes"=>$iTime,
        //            "addtime"=>date("Y-m-d H:i:s"),
        //            "username"=>$strUsername
        //        );
        //    }
        //}
        //if(count($arrInputValues)==0){
        //    ShowJsonReturnAndDie(null,true,"请至少录入一项时长");
        //}
        //$mdlLesson =new \Api\Model\AppLessonModel();
        //$db  = $mdlLesson->getCardDb();
        //$db->addAll($arrInputValues);
        //$strFeedback =trim(I("feedBack"));
        //if($strFeedback!="") // 留言不是一定要填，为空不报错
        //{
        //    $mdlParent =new \Home\Model\AppParentsModel();
        //    $dbFeedback =  $mdlParent->getFeedbackDb();
        //    $dbFeedback->add(
        //        array(
        //            "content"=>$strFeedback,
        //            "addtime"=>date("Y-m-d H:i:s"),
        //            "status"=>0
        //        ));
        //}

        ShowJsonReturnAndDie(null);
    }

    //获取书籍上次得分
    public function getBookScore(){
        $strUsername=$this->getDefaultUserName();
        $iBookID = I("bookId");
        $strSql="select b.PageCount,b.BookName,b.Dirname,isnull(p.lastscorecache,0) as lastpkscore,(select count(*) from TB_WxReadRecordBook r where r.BookID = b.ID)*5 as booktotalscore from TB_WxReadBook b left join
( select sum(score) as lastscorecache from app_pkdatadetail where username='%s' and wxreadbookid=%d) p on b.id = p.wxreadbookid
 where b.id=%d";
        $mdlLesson =new \Api\Model\AppLessonModel();
        $mdlParent =new \Api\Model\AppParentsModel();
        $db= $mdlParent->getPkDataDb();
        $arrPkInfo = $mdlParent->getPkData($strUsername,$iBookID,$iBookID);
        //die($mdlParent->getLastSql());
        $arrUserlist0 = $mdlParent->getPkUserList($strUsername,$iBookID,0);
        $arrUserlist=array();
        foreach($arrUserlist0 as $row)
        {
            $arrUserlist[] = array(
                "username"=>$row["username"],
                "avatarUrl"=>$row["avatar"],
                "name"=>$row["name"],
            );
        }
        // die(json_encode($arrPkInfo));
        $arrResult = array(
            "totalPages"=>$arrPkInfo["pagecount"],
            "bookName"=>$arrPkInfo["bookname"],
            "lastScore"=>number_format($arrPkInfo["lastpkscore"]),
            "totalScore"=>number_format($arrPkInfo["booktotalscore"]),
            "bookImageUrl"=>$mdlLesson->getBookCoverUrl($arrPkInfo["dirname"]),
            "passedUsers"=>$arrUserlist
        );
        ShowJsonReturnAndDie($arrResult);
    }

    //练习
    public function getBookAudioData(){
        /*
        *    “bookId”: 12 //书id
       “pkType”: 1 //1：和系统pk 2：和其他用户pk
       “pkUsername”: 12 //和其他用户pk时的用户username

         * */
        $iBookID = I("bookId");
        $ipkType = I("pkType");
        // $iPageID =I("page");
        $strPkUsername = I("pkUsername");
        $strUsername = $this->getDefaultUserName();
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrResult = $mdlParent->getUserPkData($iBookID,$ipkType,$strPkUsername,$strUsername);
        ShowJsonReturnAndDie($arrResult);
    }

    //获取随机pk人员
    public function getPkUsers(){
        $iBookID = I("bookId");
        $strUsername = $this->getDefaultUserName();
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrUserlist0 = $mdlParent->getPkUserList($strUsername,$iBookID,8);
        $arrUserlist=array();
        foreach($arrUserlist0 as $row)
        {
            $arrUserlist[] = array(
                "username"=>$row["username"],
                "avatar"=>$row["avatar"],
                "name"=>$row["name"]
            );
        }
        ShowJsonReturnAndDie($arrUserlist);
    }

    //获取pk结果
    public function getPkResult(){
        $strPkType =I("pkType");
        $iBookID = I("bookId");
        $strPkUsername =I("pkUsername");
        $strUsername = $this->getDefaultUserName();
        $bPkSystem = $strPkType==1;
        $mdlParent =new \Api\Model\AppParentsModel();
        $arrUsername =   $mdlParent->getPkData($strUsername,$iBookID);
        $iUserScore =$arrUsername["lastpkscore"];
        if($bPkSystem){
            $iScore =$arrUsername["booktotalscore"];
        }else{
            $arrPkUsername = $mdlParent->getPkData($strPkUsername,$iBookID);
            $iScore = $arrPkUsername["lastpkscore"];
        }
        ShowJsonReturnAndDie(array(
            "myScore"=>number_format($iUserScore),
            "pkUserScore"=>number_format($iScore)
        ));
    }

    //阅读
    public function getReadings(){
//        $strUsername = $this->getDefaultUserName();
//        $mdlLesson =new \Api\Model\AppLessonModel();
//        $arrSubType =  $mdlLesson->getYueDuSubType();
//        $arrResult =array();
//        foreach($arrSubType as $row){
//            $iTypeID = $row["id"];
//            $arrSubReadings0 =$mdlLesson->getBookListByYueDuType($strUsername,$iTypeID);
//            $arrSubReadings = array();
//            foreach($arrSubReadings0 as $row2)
//            {
//                $strbookImageUrl = $mdlLesson->getBookCoverUrl($row2["dirname"]);
//                $arrSubReadings[] = array(
//                    "bookName"=>$row2["bookname"],
//                    "bookImageUrl"=>$strbookImageUrl,
//                    "bookId"=>$row2["id"]
//                );
//            } // end   foreach($arrSubReadings0 as $row2)
//            $arrResult[] = array(
//                "className"=>$row["categoryname"],
//                "classType"=>$iTypeID,
//                "readings"=>$arrSubReadings
//            );
//        } // end  foreach($arrSubType as $row){
        $arrResult=array();
        $bannerList['imageUrl']='';
        $bannerList['url']='';
        $arrResult['bannerList'][]=$bannerList;
        $arrResult['recommendList'][]=array('name'=>'',
                                            'imageUrl'=>'',
                                            'type'=>'',
                                            'content'=>'',
                                            'count'=>'100',
                                            'duration'=>'18');
        ShowJsonReturnAndDie($arrResult);
    }




    //获取阅读某分类下所有书籍
    public function getReadingsWithType(){
        $iTypeID = I("classType");
        $strUsername = $this->getDefaultUserName();
        $mdlLesson =new \Api\Model\AppLessonModel();
        $arrResult0 =  $mdlLesson->getBookListByYueDuType($strUsername,$iTypeID);
        $arrResult=array();
        foreach($arrResult0 as $row)
        {
            $iIsCollect = $row["collectionid"]>0?1:0;
            $strCoverUrl = $mdlLesson->getBookCoverUrl($row["dirname"]);
            $arrResult[] = array(
                "bookName"=>$row["bookname"],
                "bookImageUrl"=>$strCoverUrl,
                "bookId"=>$row["id"],
                "isCollected"=>$iIsCollect
            );
        } //  foreach($arrResult0 as $row)
        ShowJsonReturnAndDie($arrResult);
    }
    
    public function joinMaterial(){
        $iBookID = I("bookId");
        $srUsername = $this->getDefaultUserName();
        $mdlLesson =new Model\AppLessonModel();
        $strError =  $mdlLesson->joinMaterial($srUsername,$iBookID);
        if($strError!="")
        {
            ShowJsonReturnAndDie(null,true,$strError);
        }
        ShowJsonReturnAndDie(null);
    }

    // 榜单排名
    public function getRank(){
        $username=trim(I('username')); //用户名 100001021
        $time=trim(I('timeType'));       //查询时间条件
        $area=trim(I('spaceType'));               //区域查询条件

        switch ($time)
        {
            case '4':
                $yearfirstday= date('Y-01-01 00:00:00');//本年开始的第一天
                $ini['addtime']=array('GT',$yearfirstday);
                break;
            case '3':
                $yearfirstday= date('Y-01-01 00:00:00');//本年开始的第一天
                $halfyearfirstday= date('Y-06-01 00:00:00');//下半年第一天
                $today= date('Y-m-d 00:00:00',time());//本日
                if(strtotime($halfyearfirstday)-strtotime($today)>0){
                    //处于上半年
                    $ini['addtime']=array('GT',$yearfirstday);
                }else{
                    //处于下半年
                    $ini['addtime']=array('GT',$halfyearfirstday);
                }
                break;
            case '2':
                $monthfirstday= date('Y-m-01 00:00:00');//本月第一天
                $ini['addtime']=array('GT',$monthfirstday);
                break;
            default:
                $weekfirstday= date('Y-m-d 00:00:00 ', strtotime('this week'));//本周第一天
                $ini['addtime']=array('GT',$weekfirstday);

        }

        //查询用户所在馆、所在市
        $uarr=MwithNoPrefix("Sys_Section")
            ->field('Sys_Section.FSectionName,Sys_Section.FCity,TB_Students.username,TB_Students.name')
            ->join('TB_Students ON Sys_Section.Fid = TB_Students.sectionid','left')
            ->where("username='".$username."'")
            ->select();
        //用户所在馆
        $section=$uarr[0]['fsectionname'];
        //用户所在市
        $city=$uarr[0]['fcity'];

        switch ($area)
        {
            case '1':
                //全国查询
                $arr=MwithNoPrefix("APP_CardLog")
                    ->field('TB_Students.username,TB_Students.name,TB_Students.avatar,sum(cardminutes) as duration')
                    ->join('TB_Students ON APP_CardLog.username = TB_Students.username')
                    ->group('TB_Students.username,TB_Students.name,TB_Students.avatar')
                    ->order('duration desc')
                    ->where($ini)
                    ->select();
                break;
            case '2':
                //根据城市查询
                $ini['Sys_Section.Fcity']=$city;
                $arr=MwithNoPrefix("Sys_Section")
                    ->field('TB_Students.username,TB_Students.name,TB_Students.avatar,sum(cardminutes) as duration')
                    ->join('TB_Students ON Sys_Section.Fid = TB_Students.sectionid')
                    ->join('APP_CardLog ON APP_CardLog.username = TB_Students.username')
                    ->group('TB_Students.username,TB_Students.name,TB_Students.avatar')
                    ->order('duration desc')
                    ->where($ini)
                    ->select();
                break;
            default:
                //根据用户所在馆 avatar据说是用户头像url字段
                $ini['Sys_Section.FSectionName']=$section;
                $arr=MwithNoPrefix("Sys_Section")
                    ->field('TB_Students.username,TB_Students.name,TB_Students.avatar,sum(cardminutes) as duration')
                    ->join('TB_Students ON Sys_Section.Fid = TB_Students.sectionid')
                    ->join('APP_CardLog ON APP_CardLog.username = TB_Students.username')
                    ->group('TB_Students.username,TB_Students.name,TB_Students.avatar')
                    ->order('duration desc')
                    ->where($ini)
                    ->select();
        }

        //查询排名
        $arr2 = i_array_column($arr, 'username');//把数组中所有username列出来
        $offset=array_search($username,$arr2); //判断username在数组中第几个
        $paiming=$offset+1;//用户的排名
        $top10=array_slice($arr,0,10); //取出前十数据
        $result=array();
        $result['myOrder']=$paiming;
        $result['myMuseum']=$section;
        $result['rankList']=$top10;

//        echo '<pre>';
//        print_r($result);
//        echo '</pre>';
        ShowJsonReturnAndDie($result);
    }



}
